<template>
  <el-date-picker
    :type="config.dateType || 'date'"
    v-model="searchValue"
    :placeholder="
      config.placeholder
        ? config.placeholder
        : $t('component.search.select_placeholder') + config.label
    "
    clearable
    :format="dateFormat"
    :value-format="shouldUseValueFormat ? valueFormat : undefined"
    :range-separator="isRangeType ? '至' : undefined"
    :start-placeholder="isRangeType ? startPlaceholder : undefined"
    :end-placeholder="isRangeType ? endPlaceholder : undefined"
    :style="{ width: '100%' }"
  ></el-date-picker>
</template>

<script setup>
import { computed } from "vue";
const props = defineProps(["model", "config"]);
const emit = defineEmits(["update"]);

const searchValue = computed({
  get() {
    return props.model;
  },
  set(value) {
    emit("update", props.config, value);
  },
});

// 根据dateType设置格式
const dateFormat = computed(() => {
  const type = props.config?.dateType || "date";
  const formatMap = {
    date: "YYYY-MM-DD",
    datetime: "YYYY-MM-DD HH:mm:ss",
    year: "YYYY",
    month: "YYYY-MM",
    week: "YYYY-[W]ww",
    daterange: "YYYY-MM-DD",
    datetimerange: "YYYY-MM-DD HH:mm:ss",
    monthrange: "YYYY-MM",
    yearrange: "YYYY",
  };
  return formatMap[type] || "YYYY-MM-DD";
});

// 判断是否为范围类型
const isRangeType = computed(() => {
  const type = props.config?.dateType || "date";
  return type.includes("range");
});

// 动态设置开始占位符
const startPlaceholder = computed(() => {
  const placeholderMap = {
    daterange: "开始日期",
    datetimerange: "开始日期时间",
    monthrange: "开始月份",
    yearrange: "开始年份",
  };
  return placeholderMap[props.config?.dateType] || "开始日期";
});

// 动态设置结束占位符
const endPlaceholder = computed(() => {
  const placeholderMap = {
    daterange: "结束日期",
    datetimerange: "结束日期时间",
    monthrange: "结束月份",
    yearrange: "结束年份",
  };
  return placeholderMap[props.config?.dateType] || "结束日期";
});

// 判断是否应该使用value-format
const shouldUseValueFormat = computed(() => {
  const type = props.config?.dateType || "date";
  // week类型不支持value-format
  return type !== "week";
});

const valueFormat = computed(() => {
  const type = props.config?.dateType || "date";
  const formatMap = {
    date: "YYYY-MM-DD",
    datetime: "YYYY-MM-DD HH:mm:ss",
    year: "YYYY",
    month: "YYYY-MM",
    daterange: "YYYY-MM-DD",
    datetimerange: "YYYY-MM-DD HH:mm:ss",
    monthrange: "YYYY-MM",
    yearrange: "YYYY",
  };
  return formatMap[type] || "YYYY-MM-DD";
});
</script>
